package com.ipet.app.util;

import android.content.Context;
import android.widget.ImageView;

import com.ipet.app.api.Api;
import com.ipet.app.bean.DisPlayImage;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by jindongping on 15/6/5.
 */
public class ImageUtil {
    private volatile static ImageUtil instance;
    private Context context;

    public static ImageUtil getInstance(Context context) {
        if (instance == null) {
            synchronized (ImageUtil.class) {
                if (instance == null) {
                    instance = new ImageUtil(context);
                }
            }
        }
        return instance;
    }

    protected ImageUtil(Context context) {
        this.context = context;
    }

    public void disPaly(String url, ImageView imageView) {
        Picasso.with(context)
                .load(Api.API_URL + "/Uploads/" + url)
                .placeholder(me.nereo.multi_image_selector.R.drawable.default_error)
                .into(imageView);
    }

    public void disPalyWithReSize(String url, ImageView imageView, int targetWidth, int targetHeight) {
        Picasso.with(context)
                .load(Api.API_URL + "/Uploads/" + url)
                .placeholder(me.nereo.multi_image_selector.R.drawable.default_error)
                .resize(targetWidth, targetHeight).centerCrop().into(imageView);
    }

    /**
     * 根据图片数量 计算图片的长宽和边距
     *
     * @param images 图片Url
     */
    public List<DisPlayImage> convertUrlToDisplayImg(String[] images, int padding) {
        padding = TDevice.dipToPx(context, padding);
        List<DisPlayImage> disPlayImages = new ArrayList<>();
        int width = 0, height = 0, imagePadding = 0;
        if (images.length >= 3) {
            imagePadding = 10;
            height = width = (TDevice.getDisplayMetrics().widthPixels) / 3 - imagePadding - padding;
        } else if (images.length == 2) {
            imagePadding = 10;
            height = width = (TDevice.getDisplayMetrics().widthPixels) / 2 - imagePadding - padding;
        } else if (images.length == 1) {
            //宽度为屏幕宽度的2/3
            width = (TDevice.getDisplayMetrics().widthPixels) * 2 / 3 - padding;
            height = ((width * TDevice.getDisplayMetrics().heightPixels) / TDevice.getDisplayMetrics().widthPixels ) * 2 / 3 - padding;
        }
        for (int i = 0; i < images.length; i++) {
            disPlayImages.add(new DisPlayImage(images[i], width, height));
        }
        return disPlayImages;
    }

}
